package Server.Model.Hall;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperic.sigar.SigarException;

import net.sf.json.JSONObject;
import network.handler.HandlerWrapperMgr;
import network.handler.NetHandlerMgr;
import network.handler.NetworkSender;
import network.handler.NodeLoadMgr;
import network.handler.NodePeerMgr;
import network.handler.ProtocolMsg;
import rank.RankDef;
import redis.protocal.DbInfoMgr;
import redis.protocal.RedisLock;
import redis.protocal.UserChargeInfo;
import redis.protocal.UserRedisInfo;
import robot.RobotMgr;
import Server.AHMJ.HFHZ.Constants;
import Server.Agent.CHttpClient;
import Server.Agent.GameAgent;
import Server.Agent.GameConfig;
import Server.Model.Base.IRoom;
import Server.Model.Base.OtherRoom;
import Server.Model.Base.SHMUser;
import Server.Model.Base.SecShmUser;
import Server.Model.Base.UserGoldChange;
import activity.ActivityMgr;
import activity.UserActionActivity;
import admin.AdminEnum;
import admin.AdminMgr;
import admin.AdminRedis;
import club.ClubEnum;
import club.ClubMgr;
import club.ClubRedis;
import common.routine.CommonZooListener;
import common.routine.GlobalRoutine;
import common.routine.GlobalSetting;
import common.routine.JsonUtils;
import common.routine.LogicRoomLockInfo;
import common.routine.MailSender;
import common.routine.MonitorInfoBean;
import common.routine.NetCommonUtil;
import common.routine.NodeInfoVo;
import common.routine.PublishDef;
import common.routine.SystemInfo;
import common.routine.SystemInfoTools;
import common.routine.CommonDef;
import common.routine.CommonDef.NodeType;
import db.Data_agentpay_push;
import db.Data_ninedt_user;
import db.Data_realpay_push;
import io.netty.channel.ChannelHandlerContext;
import logic.iface.LogicServer;
import msg.protocal.ActorEntry;
import msg.protocal.CMD_LogicWillDownMsg;
import msg.protocal.CMD_enum;
import msg.protocal.DataWrapper;
import msg.protocal.ObjectWrapper;
import msg.protocal.RedisNotifyWrapper;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import Server.Model.Base.IRoom;
import Server.Model.Base.SHMUser;


public class dthall {
	public Map<Integer, String> m_mapAvatar = new HashMap<Integer, String>();

	public Map<Integer, SHMUser> m_mapUser = new HashMap<Integer, SHMUser>();
	public Map<Integer, Integer> m_mapLinkSession = new HashMap<Integer, Integer>();
	public Map<Integer, Integer> m_mapLinkUser = new HashMap<Integer, Integer>();
	public QpGameMgr m_qpGameMgr = QpGameMgr.getInstance();
	public WxGameMgr m_wxGameMgr = WxGameMgr.getInstance();
	public GameMgr m_gameMgr = GameMgr.getInstance();
	Log log = LogFactory.getLog(this.getClass());
	private static class SingletonHolder {
		private static final dthall INSTANCE = new dthall();
	}
	public boolean m_userRankInClub = false;
	public void setUseRankInClub(boolean use){
		m_userRankInClub = use;
	}
	
	private dthall() {
		startSendSystemInfo();
		if(GlobalSetting.getInstance().getSelfNodeInfo().nodeType == NodeType.LOGIC){
			ClubMgr.getInstance();
			class LoadRebot extends TimerTask{			
				@Override
				public void run() {
					RobotMgr.getInstance().loadRobotNickName();
				}				
			}
			Timer timer = new Timer();
			LoadRebot task = new LoadRebot();
			timer.schedule(task,5000);
		}
	}
	public void onDealRoom(){
		m_qpGameMgr.onDealRoom();
	}
	public static final dthall getInstance() {
		return SingletonHolder.INSTANCE;
	}
	public List<String> getAllOnlineAccount(){
		List<String> users = new ArrayList<String>();
		Iterator<Map.Entry<Integer, SHMUser>> it = m_mapUser.entrySet().iterator();
		String currAcount = null;
		int currUid = 0;
		try{
			while (it.hasNext()) {
				Map.Entry<Integer, SHMUser> entry = it.next();
				SHMUser user = entry.getValue();
				if(user != null && user.m_lUid == 0)
					continue;
				if(user != null){
					currAcount = user.m_sAccount;
					currUid = user.m_lUid;
				}
				if(user != null && user.m_sAccount.isEmpty() == false){
					users.add(user.m_sAccount);
				}
			}
		}catch(java.lang.NullPointerException e){
			System.out.println("currAccount=" + currAcount);
			System.out.println("currUid=" + currUid);
			e.printStackTrace();
		}
		return users;
	}
	public void addUser(Integer _Uid, JSONObject value) {
		if (m_mapUser.containsKey(_Uid)) {
			// m_mapUser.remove(_Uid);
		} else {
			SHMUser shmUser = new SHMUser();
			shmUser.m_lUid = _Uid;
			shmUser.setValue(value);
			m_mapUser.put(_Uid, shmUser);
		}
	}

	public void delUser(Integer lUid) {
		if (m_mapUser.containsKey(lUid)) {
			m_mapUser.remove(lUid);
		}
	}

	public void OnClientClose(GameAgent agent) {
		try {
			int UID = agent.getUID();
			int CID = agent.getCID();

			if (UID > 0 && CID > 0) {
				m_qpGameMgr.onUserClientCloseForRoom(UID);
			}

			SHMUser user = getUserInfo(UID);
			if(user != null)
			{
				if(user.m_curRoom != null)
				{
					user.m_curRoom.OnClientClose(UID);
					user.m_curRoom = null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void linkUser(Integer dwSessionIndex, Integer lUid) {
		m_mapLinkSession.put(lUid, dwSessionIndex);
		m_mapLinkUser.put(dwSessionIndex, lUid);

	}

	public void unlinkUser(Integer dwSessionIndex, Integer lUid) {
		if (m_mapLinkSession.containsKey(lUid)) {
			int oldLinkCID = m_mapLinkSession.get(lUid);
			try {
				GameAgent old_agent = GameAgent.find_client(oldLinkCID);
				if (old_agent != null) {
					old_agent.Disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			m_mapLinkSession.remove(lUid);

			if (m_mapLinkUser.containsKey(oldLinkCID)) {
				m_mapLinkUser.remove(oldLinkCID);
			}
		}

		if (dwSessionIndex > 0) {
			Iterator<Map.Entry<Integer, Integer>> it = m_mapLinkSession.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<Integer, Integer> entry = it.next();
				int key = entry.getKey();
				int value = entry.getValue();
				if (value == dwSessionIndex) {
					System.out.println("unlink: " + key + " = " + key);
					it.remove(); // OK
				}
			}

			if (m_mapLinkUser.containsKey(dwSessionIndex)) {
				m_mapLinkUser.remove(dwSessionIndex);
			}
		}
	}
	//handle db msg
	public void handleDbWrapper(DataWrapper wrapper){
		switch(wrapper._cmd){
		case CMD_enum.DB_USERLOGIN:{
			GameAgent agent = (GameAgent)wrapper._origAgent;
			JSONObject userInfo = wrapper._dbData;
			SHMUser user = null;
			int lUid = 0;
			if(userInfo != null){
				userInfo.put("m_sIP", agent.getIP());
				lUid = userInfo.optInt("m_lUid");
				this.unlinkUser(0, lUid);
				this.linkUser(agent.getCID(), lUid);
				this.addUser(lUid,userInfo);
				user = this.getUserInfo(lUid);
			}
			if(user != null && wrapper._attachOp.equals("hall_wxlogin")){
				CMD_WXLoginSuccess cmd = new CMD_WXLoginSuccess();
				cmd.setUser(user);
				
				String sUserIcon = null;
				String nickName = null;
				if (wrapper._origJson.has("user_icon")) {
					sUserIcon = wrapper._origJson.optString("user_icon");
				}
				if(wrapper._origJson.has("user_nick")){
					nickName = wrapper._origJson.optString("user_nick");
					user.getNickName(nickName);
				}
				if(sUserIcon == null && wrapper._origJson.has("sUserIcon")){
					sUserIcon = wrapper._origJson.optString("sUserIcon");
				}
				cmd.userIcon = sUserIcon;
				String sData = cmd.getJsonData();
				GameAgent.setUser(agent.getCID(), user);
				this.onSend(lUid, sData);
				if(sUserIcon != null){
					m_mapAvatar.put(lUid, sUserIcon);
					DbInfoMgr.getInstance().setUserAvatarUrl(lUid,sUserIcon);
				}else if(wrapper._origJson.containsKey("sUserIcon")){
					int uid = (int)wrapper._dbData.get("m_lUid");
					String userIcon = wrapper._origJson.getString("sUserIcon");
					m_mapAvatar.put(uid, userIcon);	
					DbInfoMgr.getInstance().setUserAvatarUrl(uid,userIcon);
				}
				int bindAgent = wrapper._dbData.getInt("m_bindAgent");
				if(bindAgent > 0){
					String sNickName = wrapper._dbData.getString("m_sNickName");
					BindAgent(lUid, sNickName, bindAgent);
				}
				NotifyMgr.getInstance().Handle_OnClientLogin(lUid);
				DbInfoMgr.getInstance().setUserLoginTime("" + lUid);
			}else if (user != null && wrapper._attachOp.equals("hall_login")){
				CMD_LoginSuccess cmd = new CMD_LoginSuccess();
				cmd.setUser(user);
				cmd.userIcon = PublishDef.getDefaultHeadAvatar();
				String sData = cmd.getJsonData();
				GameAgent.setUser(agent.getCID(), user);
				this.onSend(lUid, sData);
				DbInfoMgr.getInstance().setUserAvatarUrl(lUid,cmd.userIcon);
				NotifyMgr.getInstance().Handle_OnClientLogin(lUid);
				DbInfoMgr.getInstance().setUserLoginTime("" + lUid);
			}else if (wrapper._attachOp.equals("dwc_login")){
				if(userInfo != null){
					CMD_WXLoginSuccess cmd = new CMD_WXLoginSuccess();
					cmd.setUser(user);
					UserRedisInfo redisInfo = new UserRedisInfo(JSONObject.fromObject(DbInfoMgr.getInstance().getUserRedisSaveInfo("" + lUid)));
					String sUserIcon = redisInfo.json.optString("headurl");
					String nickName = userInfo.optString("m_sNickName");
					user.getNickName(nickName);
					cmd.userIcon = sUserIcon;
					cmd.loginType = "dwc_login";
					String sData = cmd.getJsonData();
					GameAgent.setUser(agent.getCID(), user);
					this.onSend(lUid, sData);
					if(sUserIcon != null){
						m_mapAvatar.put(lUid, sUserIcon);
						DbInfoMgr.getInstance().setUserAvatarUrl(lUid,sUserIcon);
					}else if(wrapper._origJson.containsKey("sUserIcon")){
						int uid = (int)wrapper._dbData.get("m_lUid");
						String userIcon = wrapper._origJson.getString("sUserIcon");
						m_mapAvatar.put(uid, userIcon);	
						DbInfoMgr.getInstance().setUserAvatarUrl(uid,userIcon);
					}
					NotifyMgr.getInstance().Handle_OnClientLogin(lUid);
					DbInfoMgr.getInstance().setUserLoginTime("" + lUid);
				}else{
					CMD_LoginFailed cmd = new CMD_LoginFailed();
					cmd.m_iErrorType = 1;
					cmd.m_sErrorMsg = "找不到用户或者密码错误";
					String sData = cmd.getJsonData();
					GameAgent.Send(agent.getCID(), sData);
				}
			}else if(user != null && wrapper._attachOp.equals("hall_relogin")){
				System.out.println("用户重新加载成功:" + agent.getUid());
				GameAgent.setUser(agent.getCID(), user);
				String origobj = wrapper._origJson.getString("origobj");
				JSONObject origJson = JSONObject.fromObject(origobj);
				Handle_Res_Connection(agent,origJson,agent.getCID());
				NotifyMgr.getInstance().Handle_OnClientLogin(lUid);
				DbInfoMgr.getInstance().setUserLoginTime("" + lUid);
			}else if(user != null && wrapper._attachOp.equals("hall_login_joinroom")){
				agent.setUser(user);
				agent._uid = String.valueOf(lUid);
				m_qpGameMgr.Handle_OnJoinRoom(agent,wrapper._origJson);
			}
			break;
		}
		}
	}
	public void handleRedisNotifyWrapper(RedisNotifyWrapper wrapper){
		switch(wrapper._cmd){
		case CMD_enum.DB_REAL_PAY:{
			int uid = wrapper._uid;
			GameAgent agent = LogicServer.getUserAgent(String.valueOf(uid));
			if(agent == null){
				agent = LogicServer.getUserAgent(wrapper._account);
				if(agent == null){
					//不在此服务器上,用户不在线则不处理
					return;
				}
			}

			Data_ninedt_user redisUser = JsonUtils.deserialize(wrapper._userData, Data_ninedt_user.class);
			Data_realpay_push payInfo = JsonUtils.deserialize(wrapper._notifyData,Data_realpay_push.class);
			SHMUser user = agent.getUser();
			if(redisUser != null && payInfo != null && user != null){
				if(true || user.getGem(0) != redisUser.m_lTotalGem){
					if(user.getGem(0) == (redisUser.m_lTotalGem - payInfo.addGem)){
						System.out.println("用户:" + uid + " 后台代理充值");
						user.getGem(payInfo.addGem);
						user.getCoin(payInfo.addCoin);
						user.getCard(payInfo.addCard);
						
						CMD_PaySuccessNotice cmd = new CMD_PaySuccessNotice();
						cmd.m_lTotalCoin = user.getCoin(0);
						cmd.m_lTotalGem = user.getGem(0);
						cmd.m_lTotalCard = user.getCard(0);

						String sData = cmd.getJsonData();
						String account = LogicServer.getUserAccount(agent);
						ProtocolMsg sendmsg = NetworkSender.genProtocolMsg(CMD_enum.LOGIC_TOCLIENT, sData,account);
						
						ObjectWrapper newwrapper = new ObjectWrapper();
						newwrapper._obj = sendmsg;
						newwrapper._actorEntry = new ActorEntry(account,"","");
						NetHandlerMgr.getInstance().pushMsgNoNotify(newwrapper);
					}else{
						//以redis 上为准
						user.m_lTotalGem = redisUser.m_lTotalGem;
						user.m_lTotalCoin = redisUser.m_lTotalCoin;
						user.m_lTotalCard = redisUser.m_lTotalCard;
						
						CMD_PaySuccessNotice cmd = new CMD_PaySuccessNotice();
						cmd.m_lTotalCoin = user.getCoin(0);
						cmd.m_lTotalGem = user.getGem(0);
						cmd.m_lTotalCard = user.getCard(0);

						String sData = cmd.getJsonData();
						String account = LogicServer.getUserAccount(agent);
						ProtocolMsg sendmsg = NetworkSender.genProtocolMsg(CMD_enum.LOGIC_TOCLIENT, sData,account);
						
						ObjectWrapper newwrapper = new ObjectWrapper();
						newwrapper._obj = sendmsg;
						newwrapper._actorEntry = new ActorEntry(account,"","");
						NetHandlerMgr.getInstance().pushMsgNoNotify(newwrapper);
					}
				}
			}
			break;
		}
		case CMD_enum.DB_AGENT_PAY:{
			//处理代理pay，现在是通过遍历redis实现，这里没有实现
			int uid = wrapper._uid;
			GameAgent agent = LogicServer.getUserAgent(String.valueOf(uid));
			if(agent == null){
				agent = LogicServer.getUserAgent(wrapper._account);
				if(agent == null){
					//不在此服务器上,用户不在线则不处理
					return;
				}
			}
			Data_ninedt_user redisUser = JsonUtils.deserialize(wrapper._userData, Data_ninedt_user.class);
			Data_agentpay_push payInfo = JsonUtils.deserialize(wrapper._notifyData,Data_agentpay_push.class);
			SHMUser user = agent.getUser();
			if(redisUser != null && payInfo != null && user != null){
				if(true || user.getGem(0) != redisUser.m_lTotalGem){
					if(user.getGem(0) == (redisUser.m_lTotalGem - payInfo.addGem)){
						//正确充值
						System.out.println("用户:" + uid + " 后台代理充值");
						user.m_lTotalGem = redisUser.m_lTotalGem;
						user.m_lTotalCoin = redisUser.m_lTotalCoin;
						user.m_lTotalCard = redisUser.m_lTotalCard;
						
						CMD_PaySuccessNotice cmd = new CMD_PaySuccessNotice();
						cmd.m_lTotalCoin = user.getCoin(0);
						cmd.m_lTotalGem = user.getGem(0);
						cmd.m_lTotalCard = user.getCard(0);

						String sData = cmd.getJsonData();
						String account = LogicServer.getUserAccount(agent);
						ProtocolMsg sendmsg = NetworkSender.genProtocolMsg(CMD_enum.LOGIC_TOCLIENT, sData,account);
						
						ObjectWrapper newwrapper = new ObjectWrapper();
						newwrapper._obj = sendmsg;
						newwrapper._actorEntry = new ActorEntry(account,"","");
						NetHandlerMgr.getInstance().pushMsgNoNotify(newwrapper);
					}else{
						//以redis 上为准
						user.m_lTotalGem = redisUser.m_lTotalGem;
						user.m_lTotalCoin = redisUser.m_lTotalCoin;
						user.m_lTotalCard = redisUser.m_lTotalCard;
						
						CMD_PaySuccessNotice cmd = new CMD_PaySuccessNotice();
						cmd.m_lTotalCoin = user.getCoin(0);
						cmd.m_lTotalGem = user.getGem(0);
						cmd.m_lTotalCard = user.getCard(0);

						String sData = cmd.getJsonData();
						String account = LogicServer.getUserAccount(agent);
						ProtocolMsg sendmsg = NetworkSender.genProtocolMsg(CMD_enum.LOGIC_TOCLIENT, sData,account);
						
						ObjectWrapper newwrapper = new ObjectWrapper();
						newwrapper._obj = sendmsg;
						newwrapper._actorEntry = new ActorEntry(account,"","");
						NetHandlerMgr.getInstance().pushMsgNoNotify(newwrapper);
					}
				}
			}
			break;
		}
		case CMD_enum.USER_BIND_INVITOR:{
			//用户被绑定了邀请，用户的score变化了
			int uid = wrapper._uid;
			GameAgent agent = LogicServer.getUserAgent(String.valueOf(uid));
			if(agent == null){
				//不在此服务器上,用户不在线则不处理
				return;
			}
			JSONObject json = JSONObject.fromObject(wrapper._notifyData);
			CMD_GetBind_Invitor cmd = new CMD_GetBind_Invitor();
			cmd.m_bindId = json.optInt("uid");
			cmd.m_bindAccount = json.optString("account");
			cmd.m_addScore = json.optInt("score");
			String rankStr = DbInfoMgr.getInstance().getUserRankByUid(uid);
			RankDef rankDef = JsonUtils.deserialize(rankStr,RankDef.class);
			cmd.m_totalScore = rankDef.m_score;			

			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
			break;
		}
		}
	}
	public void BindAgent(int _Uid,String sNickName,int agent_id) {
		System.out.println("_Uid=" + _Uid + "agent_id=" + agent_id);
		CHttpClient c = new CHttpClient();
		String strResponse = c.reguserinfo(_Uid, agent_id, sNickName, "", "");

		//更新agent,临时解决方案
		DbInfoMgr.getInstance().Handle_OnUpdateBindAgent(_Uid, agent_id);
		if(true){
			SHMUser shmuser = this.getUserInfo(_Uid);
			if(shmuser != null)
				shmuser.getAgent(agent_id);
		}
		try{
			JSONObject value = JSONObject.fromObject(strResponse);

			String code = value.optString("code");
			String msg = value.optString("msg");

			
			if ("OK".equals(code)) {
				SHMUser shmuser = this.getUserInfo(_Uid);
				shmuser.getAgent(agent_id);
			} else {

			}
		}catch(net.sf.json.JSONException e){
			e.printStackTrace();
		}
	}
	public SHMUser getUserInfo(int _Uid) {
		if (m_mapUser.containsKey(_Uid)) {
			return m_mapUser.get(_Uid);
		}
		if(_Uid == 0){
			//0号用户为虚拟用户，用来绕开创建房间限制的
			SHMUser user = new SHMUser();
			user.m_lUid = 0;
			user.m_lTotalGem = 10000;
			m_mapUser.put(_Uid, user);
			return user;
		}
		return null;
	}
	public void addRobotUser(SHMUser user){
		if(m_mapUser.containsKey(user.m_lUid)){
			return;
		}
		m_mapUser.put(user.m_lUid, user);
	}
	public SecShmUser getSecurityUserInfo(int _Uid){
		SHMUser user = null;
		if(m_mapUser.containsKey(_Uid)){
			user = m_mapUser.get(_Uid);
		}
		if(user != null){
			return new SecShmUser(user);
		}else{
			return new SecShmUser(_Uid);
		}
	}
	public List<String> m_vecRobotName = new ArrayList<String>();

	public void readRobotName() {
		try {
			String encoding = "UTF8";
			File file = new File("./nickname.csv");
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					//System.out.println(lineTxt);
					m_vecRobotName.add(lineTxt);
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
	}
	int random(int iMin, int iMax) {
		Random ra = new Random();
		return ra.nextInt(iMax - iMin) + iMin;
	}	

	public void Request_Client_GpsData(SHMUser user){
		//request submit gps data after 20s
		class GpsTask extends TimerTask{
			public int _uid;
			@Override
			public void run() {
				CMD_Request_GPS gpsCmd = new CMD_Request_GPS();
				String sData = gpsCmd.getJsonData();
				onSend(_uid,sData);				
			}
		}
		GpsTask task = new GpsTask();
		task._uid = user.getUid();
		Timer timer = new Timer();
		timer.schedule(task, 10000);
	}
	
	public void Handle_OnLogin(GameAgent agent, JSONObject root, int linkId) {	
		try {
			int lUid = 0;
			String sPwd = "", sAccount = "";
			if (root.has("uid"))
				lUid = root.optInt("uid");
			if (root.has("pwd"))
				sPwd = root.optString("pwd");
			if (root.has("account"))
				sAccount = root.optString("account");
			if (lUid > 0) {
				SHMUser user = getUserInfo(lUid);
				if (user != null) {
					String userPassword = user.getField("m_sPassword");
					String userAccount = user.getField("m_sAccount");
					if (userAccount.equalsIgnoreCase(sAccount)) {
						user.updateLoginTime(System.currentTimeMillis() / 1000);

						unlinkUser(0, user.getUid());

						linkUser(linkId, user.getUid());
						
						agent.setUser(user);
						{
							CMD_LoginSuccess cmd = new CMD_LoginSuccess();
							cmd.setUser(user);
							cmd.userIcon = PublishDef.getDefaultHeadAvatar();
							String sData = cmd.getJsonData();
							onSend(user.getUid(), sData);
						}

						{
							m_qpGameMgr.Handle_OnUserRoom(agent, null);
							NotifyMgr.getInstance().Handle_OnClientLogin(lUid);
						}
						return;
					}
				}
			}
			root.put("dwSessionIndex", linkId);
			LogicServer.pushDbHallLoginMsg(agent,root);
			//GameDB.getInstance().push_task(agent, root);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	public void Handle_OnDwcLogin(GameAgent agent, JSONObject root, int linkId){
		
	}
	// 登陆

	public void Handle_OnQQLogin(JSONObject root, int linkId) {
		try {

		} catch (Exception e) {

		}
	}// QQ登陆
	public void Handle_OnGetGpsData(GameAgent agent,JSONObject root){
		int lUid = 0;
		if (root.has("uid"))
			lUid = root.optInt("uid");
		if (lUid > 0) {
			SHMUser user = getUserInfo(lUid);
			if(user != null){
				float lng = Float.parseFloat(root.getString("lng"));
				float lat = Float.parseFloat(root.getString("lat"));
				user.setLocateInfo(lng,lat);
				DbInfoMgr.getInstance().setUserGps(String.valueOf(user.getUid()), lng, lat);
			}
		}
	}
	public void Handle_OnGetLocationData(GameAgent agent,JSONObject root){
		int lUid = 0;
		if(root.has("uid"))
			lUid = root.optInt("uid");
		if(lUid > 0){
			SHMUser user = getUserInfo(lUid);
			String loc = root.optString("loc");
			if(user != null){
				user.setGpsLoc(loc);
				DbInfoMgr.getInstance().setUserLocation(String.valueOf(user.getUid()), loc);
			}
		}
	}
	public void Handle_OnWXLogin(GameAgent agent, JSONObject root, int linkId) {

		try {
			int lUid = 0;
			String sPwd = "", sAccount = "", sUserID = "", sUserIcon = "";
			if (root.has("uid"))
				lUid = root.optInt("uid");
			if (root.has("user_id"))
				sUserID = root.optString("user_id");
			if (root.has("user_icon"))
				sUserIcon = root.optString("user_icon");
			sAccount = sUserID;
			if (lUid > 0) {
				SHMUser user = getUserInfo(lUid);
				if (user != null) {
					m_mapAvatar.put(lUid, sUserIcon);
					DbInfoMgr.getInstance().setUserAvatarUrl(lUid,sUserIcon);

					String userPassword = user.getField("m_sPassword");
					String userAccount = user.getField("m_sAccount");

					if (userAccount.equalsIgnoreCase(sAccount) && userPassword.equalsIgnoreCase(sPwd)) {
						user.updateLoginTime(System.currentTimeMillis() / 1000);

						unlinkUser(0, user.getUid());
						linkUser(agent.getCID(), user.getUid());

						agent.setUser(user);
						{
							CMD_WXLoginSuccess cmd = new CMD_WXLoginSuccess();
							cmd.setUser(user);
							cmd.userIcon = sUserIcon;
							String sData = cmd.getJsonData();
							onSend(user.getUid(), sData);
							GameAgent.setUser(agent.getCID(), user);
						}
						{
							m_qpGameMgr.Handle_OnUserRoom(agent, null);
							NotifyMgr.getInstance().Handle_OnClientLogin(lUid);
						}
						{
							Request_Client_GpsData(user);
						}
						return;
					}
				}
			}
			root.put("dwSessionIndex", linkId);
			LogicServer.pushDbWxLoginMsg(agent,root);
			//GameDB.getInstance().push_task(agent, root);//zws TODO
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}// WX登陆
	
	/**
	 * 断线后重连websocket绑定用户
	 * @param agent
	 * @param root
	 * @param linkId
	 */
	public void Handle_Res_Connection(GameAgent agent, JSONObject root, int linkId) {
		try {
			int lUid = 0;
			String scene = "";
			if (root.has("uid")){
				lUid = root.optInt("uid");
			}
			if(root.has("scene")){
				scene = root.optString("scene");
			}
			if (lUid > 0) {
				SHMUser user = getUserInfo(lUid);
				if (user != null) {
					user.updateLoginTime(System.currentTimeMillis() / 1000);
//					unlinkUser(0, user.getUid());
//					linkUser(agent.getCID(), user.getUid());
					agent.setUser(user);
					// 游戏场景 断线重连业务
					if(!LogicServer.hasSuchAccountAgent(agent))
						LogicServer.addUserAgent(String.valueOf(lUid),agent);
					if(scene != null && "gameScene".equals(scene)){
						if(m_qpGameMgr.isUserInRoom(lUid)){
							m_qpGameMgr.Handle_Res_Connection_JoinRoom(agent,root,m_qpGameMgr.getUserInRoomId(lUid));
						}else{
							JSONObject json = new JSONObject();
							json.put("command",root.optString("msgtype"));
							json.put(root.optString("msgtype"), "dismissroom|");
							agent.SendMessage(json.toString());
						}
					}
				
					return;
				}
			}
			root.put("dwSessionIndex", linkId);
			LogicServer.pushDbHallLoginMsg(agent,root);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}


	static public boolean needReboot = false;
	public void Handle_OnNeedReboot(){
		needReboot = true;
		m_qpGameMgr.Handle_OnCheckOverTimeRoom();
		this.Handle_OnReboot();
	}
	public void Handle_OnReboot(){
		if(needReboot == false)
			return;
		if(!m_qpGameMgr.hasUsedRoomExist()){
			System.out.println("系统准备重启");
			System.exit(0);
		}
	}
	// 禄禄avatar
	public void Handle_OnUserOffline(int uid){
		GameAgent agent = GameAgent.findAgentByUid(uid);
		if (agent!=null) {
			agent.CloseChannel();
		}
	}

	public int Handle_OnGetCurUserNum(){
		int count = 0;
		Iterator<Map.Entry<Integer, GameAgent>> itGamer = GameAgent.agents.entrySet().iterator();
		while (itGamer.hasNext()) {
			Map.Entry<Integer, GameAgent> agents = itGamer.next();
			if(agents != null){
				GameAgent agent = agents.getValue();
				if(agent != null){
					SHMUser value = agent.user;
					if(value != null)
						count++;
				}
			}
		}
		return count;
	}

	public void startSendSystemInfo(){
		class SendSystemInfo extends TimerTask{
			@Override
			public void run() {
				try {
					String info = "我的ip:";
					List<String> data = NetCommonUtil.getLocalIp();
					for(int i = 0;i < data.size();i++){
						info += data.get(i) + ";";						
					}
					info += "我的端口:" + GlobalSetting.getInstance().getSelfNodeInfo().port + ";";
					NodeInfoVo vo = GlobalSetting.getInstance().getSelfNodeInfo();
					if(vo.nodeType == NodeType.LOGIN){
						info += "登录";
					}else if(vo.nodeType == NodeType.GATE){
						info += "网关";
					}else{
						info += "逻辑";
					}
					try {
						MailSender.SendSystemInfo(info);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (SocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		Timer timer = new Timer();
		SendSystemInfo task = new SendSystemInfo();
		timer.schedule(task,1000 * 24 * 60 * 60,1000 * 24 * 60 * 60);
	}

	public void Handle_OnAvatar(int _Uid, JSONObject root) {
		try {

		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}// 换avatar

	static ArrayList<String> top = new ArrayList<String>();
	public List<String> fakeTop100UserInfo(){
		if(top.size() != 0)
			return top;
		for(int i = 0;i < 100;i++){
			RankDef def = new RankDef(2000 +i,"Abc" + i,this.random(100,10000));
			def.m_prevScore = this.random(1000, 2000);
			def.m_rank = i + 1;
			def.m_prevRank = this.random(1000, 2000);
			top.add(JsonUtils.serialize(def));
		}
		return top;
	}
	public void Handle_OnGetUserInvitor(GameAgent agent,JSONObject root){
		int uid = agent.getUid();
		String info = "";//接口移除DbInfoMgr.getInstance().getUserInviterBind(uid);
		if(info == null)
			return;
		int invitor = Integer.parseInt(info);
		if(invitor != 0){
			CMD_GetSelf_Invitor cmd = new CMD_GetSelf_Invitor();
			cmd.m_invitor = invitor;
			
			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
		}
	}
	public void Handle_OnTop100RankInfo(GameAgent agent,JSONObject root){
		//root中含有fromIndex，从那个开始，每次请求20个数据，ws对数据量有限制，100个应该发送不过去
		try{
			int uid = agent.getUid();
			int fromIndex = root.getInt("fromIndex");
			List<String> top = DbInfoMgr.getInstance().getRankTop100FromRedis();
			int num = Math.min(100,top.size() - fromIndex);
			List<String> needs = new ArrayList<String>();
			for(int i = 0;i < num;i++){
				needs.add(top.get(fromIndex + i));
			}
			CMD_Rank_Top100_Info cmd = new CMD_Rank_Top100_Info(needs);
			cmd.setIndexAndNum(fromIndex, num);
			cmd.setTopNum(top.size());
			

			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}

	static ArrayList<String> prevTop = new ArrayList<String>();
	public List<String> fakePrevTop100UserInfo(){
		if(prevTop.size() != 0)
			return prevTop;
		for(int i = 0;i < 100;i++){
			RankDef def = new RankDef(2000 +i,"Abc" + i,this.random(100,10000));
			def.m_prevScore = this.random(1000, 2000);
			def.m_rank = i + 1;
			def.m_prevRank = this.random(1000, 2000);
			prevTop.add(JsonUtils.serialize(def));
		}
		return prevTop;
	}
	public void Handle_OnPrevTop100RankInfo(GameAgent agent,JSONObject root){
		//root中含有fromIndex，从那个开始，每次请求20个数据，ws对数据量有限制，100个应该发送不过去
		try{
			int uid = agent.getUid();
			int fromIndex = root.getInt("fromIndex");
			List<String> top = DbInfoMgr.getInstance().getPrevRankTop100FromReids();
			if(fromIndex >= top.size()){
				return;
			}
			int num = Math.min(100,top.size() - fromIndex);
			List<String> needs = new ArrayList<String>();
			for(int i = 0;i < num;i++){
				needs.add(top.get(fromIndex + i));
			}
			CMD_Rank_Top100_Info cmd = new CMD_Rank_Top100_Info(needs);
			cmd.setIndexAndNum(fromIndex, num);
			cmd.setTopNum(top.size());
			cmd.setIsPrevRank();

			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	static String selfRankInfo = null;
	public String fakeSelfUserRankInfo(){
		if(selfRankInfo != null)
			return selfRankInfo;
		RankDef def = new RankDef(0,"我的",0);
		def.m_prevScore = 0;
		def.m_rank = 9999;
		def.m_prevRank = 0;
		selfRankInfo = JsonUtils.serialize(def);
		return selfRankInfo;
	}
	public boolean Handle_OnIsUserGotHuaFei(GameAgent agent){
		int uid = agent.getUid();
		List<String> top = DbInfoMgr.getInstance().getPrevRankTop100FromReids();
		int size = Math.min(10,top.size());
		for(int i = 0;i < size;i++){
			String info = top.get(i);
			RankDef rank = JsonUtils.deserialize(info,RankDef.class);
			if(rank != null && rank.m_userId == uid)
				return true;
		}
		return false;
	}
	public boolean Handle_OnIsUserDrawHuaFei(GameAgent agent){
		int uid = agent.getUid();
		List<String> top = DbInfoMgr.getInstance().getPrevRankTop100FromReids();
		int size = Math.min(10,top.size());
		for(int i = 0;i < size;i++){
			String info = top.get(i);
			RankDef rank = JsonUtils.deserialize(info,RankDef.class);
			if(rank != null && rank.m_userId == uid && rank.m_drawed == 1)
				return true;
		}
		return false;
	}
	public void Handle_OnSetUserDrawHuaFei(GameAgent agent){
		int uid = agent.getUid();
		List<String> top = DbInfoMgr.getInstance().getPrevRankTop100FromReids();
		int size = Math.min(10,top.size());
		for(int i = 0;i < size;i++){
			String info = top.get(i);
			RankDef rank = JsonUtils.deserialize(info,RankDef.class);
			if(rank != null && rank.m_userId == uid && rank.m_drawed == 0){
				rank.m_drawed = 1;
				String str = JsonUtils.serialize(rank);
				DbInfoMgr.getInstance().setPrevRankDataToRedis(i,str);
			}
		}
	}
	public void Handle_OnMyRankInfo(GameAgent agent,JSONObject root){
		try{
			int uid = agent.getUid();
			String info = DbInfoMgr.getInstance().getUserRankByUid(uid);
			CMD_Rank_Info cmd = new CMD_Rank_Info();
			if(info == null){
				String sData = cmd.getJsonData();
				agent.SendMessage(sData);
			}else{
				RankDef rank = JsonUtils.deserialize(info,RankDef.class);
				cmd.setRankInfo(rank);
				String sData = cmd.getJsonData();
				agent.SendMessage(sData);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	public void Handle_OnBindInviter(GameAgent agent,JSONObject root){
		int uid = agent.getUid();
		String binded = "";//接口移除DbInfoMgr.getInstance().getUserInviterBind(uid);
		int bid = 0;
		if(binded != null){
			bid = Integer.parseInt(binded);
		}
		if(bid == 0){
			int invitor = root.optInt("invitor");
			String invitorInfo = DbInfoMgr.getInstance().getUserByUid(invitor);
			if(invitorInfo == null){
				CMD_Bind_Invitor cmd = new CMD_Bind_Invitor();
				cmd.m_invitor = invitor;
				cmd.m_result = ErrorDef.BIND_INVITOR_NOFOUND;//找不到要绑定的用
				String sData = cmd.getJsonData();
				agent.SendMessage(sData);
			}else{
				//注意这里的绑定邀请的可能在别的服务器上
				Data_ninedt_user invitorUser = JsonUtils.deserialize(invitorInfo, Data_ninedt_user.class);
				//接口移除DbInfoMgr.getInstance().setUserInviterBind(uid,invitor);
				CMD_Bind_Invitor cmd = new CMD_Bind_Invitor();
				cmd.m_invitor = invitor;
				cmd.m_result = ErrorDef.BIND_INVITOR_SUCCESS;
				String sData = cmd.getJsonData();
				agent.SendMessage(sData);
				
				UserActionActivity activity = ActivityMgr.getInstance().handleBindInvitorAction(uid);
				int expGet = 0;
				if(activity.m_useActioned){
					expGet = activity.m_expGet;
				}else{
					return;
				}
				RedisLock locker = DbInfoMgr.getInstance().getRedisLock(String.valueOf(invitor));
				locker.lock();
				try {
					String rankInfo = DbInfoMgr.getInstance().getUserRankByUid(invitor);
					RankDef rankDef = JsonUtils.deserialize(rankInfo,RankDef.class);
					rankDef.m_score += expGet;
					DbInfoMgr.getInstance().setUserRankInfo(invitor,JsonUtils.serialize(rankDef));
				} finally {
					locker.unlock();
				}
				JSONObject attach = new JSONObject();
				attach.put("uid",uid);
				attach.put("account",agent.user.m_sAccount);
				attach.put("score", expGet);
				DbInfoMgr.getInstance().pubRedisSubMsg(CMD_enum.USER_BIND_INVITOR, invitor,invitorUser.m_sAccount,attach.toString());
			}
		}else{
			CMD_Bind_Invitor cmd = new CMD_Bind_Invitor();
			cmd.m_invitor = bid;
			cmd.m_result = ErrorDef.BIND_INVITOR_ALREADY;
			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
		}
	}
	public void Handle_OnGetBindInviter(GameAgent agent,JSONObject root){
		return;
	}

	public String Handle_OnGetUserAvatar(int _Uid){
		if(m_mapAvatar.containsKey(_Uid)){
			return m_mapAvatar.get(_Uid);
		}else{
			String url = DbInfoMgr.getInstance().getUserAvatarUrl(_Uid);
			if(url != null && !url.equals("")){
				m_mapAvatar.put(_Uid, url);
				return url;
			}else{				
				return RobotMgr.getInstance().getRobotAvatar(_Uid);
			}
		}
	}
	public void Handle_OnUserAvatar(GameAgent agent, JSONObject root) {
		try {
			Integer _Uid = agent.getUid();
			CMD_S_Avatar cmd = new CMD_S_Avatar();
			cmd.m_lUid = _Uid;
			if (m_mapAvatar.containsKey(_Uid)) {
				cmd.szAvatarURL = m_mapAvatar.get(_Uid);
			} else {
				String url = DbInfoMgr.getInstance().getUserAvatarUrl(_Uid);
				if(url == null){
					cmd.szAvatarURL = PublishDef.getDefaultHeadAvatar();
				}else{
					m_mapAvatar.put(_Uid, url);
					cmd.szAvatarURL = url;
				}
			}

			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}

	public void Handle_OnShareTimeline(GameAgent agent, JSONObject root) {
		try {
			Integer _Uid = agent.getUid();
			SHMUser shmuser = getUserInfo(_Uid);
			if (shmuser == null)
				return;
			Long prev = 0L;
			Long tnow = System.currentTimeMillis() / 1000;
			String prevtime = DbInfoMgr.getInstance().getUserControlInfo(String.valueOf(_Uid), "OnShareTimeline");
			if(prevtime != null){
				prev = Long.parseLong(prevtime);
			}
			if ((tnow - prev) > 15 * 3600) {
				DbInfoMgr.getInstance().setUserControlInfo(String.valueOf(_Uid), "OnShareTimeline",String.valueOf(tnow));
				CMD_S_ShareTimeLine cmd = new CMD_S_ShareTimeLine();
				cmd.m_lUid = (long) _Uid;
				cmd.m_lTotalGem = (long) shmuser.getGem(12);
				String sData = cmd.getJsonData();
				agent.SendMessage(sData);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void Handle_OnGetZhuanPan(GameAgent agent,JSONObject root){
		SHMUser shmuser = getUserInfo(agent.getUID());
		if (shmuser == null)
			return;
		
		Long tnow = System.currentTimeMillis() / 1000;
		if(tnow - shmuser.getLastShareTime() < 24 * 3600){
			return;
		}
		shmuser.updateShareTime(tnow);
		Integer[] rewards = {0,100,1,0,2,10,50,0,1,0,0,5};
		int random = (int) Math.random() * 1000;
		int index = 0;
		if(random > 970)
			index = 1;
		else if(random > 920)
			index = 6;
		else{
			random %= 12;
			if(random == 1 || random == 6)
				random += 1 + Math.random() * 2;
			index = random;
		}
		CMD_S_ZhuanPan cmd = new CMD_S_ZhuanPan();
		cmd.m_lUid = agent.getUID();
		cmd.m_lRotateToGeZi = index;
		cmd.m_lAddGem = rewards[index];
		shmuser.getGem(cmd.m_lAddGem);
		cmd.m_lTotalGem = shmuser.getGem(0);
		
		String sData = cmd.getJsonData();
		agent.SendMessage(sData);
	}
	public void Handle_OnDuiHuan(GameAgent agent, JSONObject root) {
		try {
			Integer _Uid = agent.getUid();
			SHMUser shmuser = getUserInfo(_Uid);
			if (shmuser == null)
				return;

			String from_type = root.optString("from_type");
			String to_type = root.optString("to_type");
			Integer amount = root.optInt("amount");
			
			if(from_type.equalsIgnoreCase("GEM") && to_type.equalsIgnoreCase("COIN"))
			{
				int addGem = 0;int addCoin = 0;
				if(amount == 1)
				{
					addGem = -1;
					addCoin = 30000;
				}
				if(amount == 10)
				{
					addGem = -10;
					addCoin = 300000;
				}
				if(amount == 100)
				{
					addGem = -100;
					addCoin = 3000000;
				}
				CMD_S_DuiHuan cmd = new CMD_S_DuiHuan();
				cmd.m_lUid = _Uid;
				if(shmuser.getGem(0) >= 0 - addGem)
				{
					cmd.cbResult = 0;
					cmd.m_lTotalGem = shmuser.getGem(addGem);
					cmd.m_lTotalCoin = shmuser.getCoin(addCoin);
				}else{
					cmd.cbResult = 1;
					cmd.m_lTotalGem = shmuser.getGem(0);
					cmd.m_lTotalCoin = shmuser.getCoin(0);
				}

				String sData = cmd.getJsonData();
				agent.SendMessage(sData);
			}
			if(from_type.equalsIgnoreCase("COIN") && to_type.equalsIgnoreCase("GEM"))
			{
				int addGem = 0;int addCoin = 0;
				if(amount == 30000)
				{
					addGem = 1;
					addCoin = -30000;
				}
				if(amount == 300000)
				{
					addGem = 10;
					addCoin = -300000;
				}
				if(amount == 3000000)
				{
					addGem = 100;
					addCoin = -3000000;
				}
				CMD_S_DuiHuan cmd = new CMD_S_DuiHuan();
				cmd.m_lUid = _Uid;
				cmd.cbResult = 0;
				if(shmuser.getCoin(0) >= 0 - addCoin)
				{
					cmd.cbResult = 0;
					cmd.m_lTotalGem = shmuser.getGem(addGem);
					cmd.m_lTotalCoin = shmuser.getCoin(addCoin);
				}else{
					cmd.cbResult = 1;
					cmd.m_lTotalGem = shmuser.getGem(0);
					cmd.m_lTotalCoin = shmuser.getCoin(0);
				}
				String sData = cmd.getJsonData();
				agent.SendMessage(sData);
			}	

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	public void Handle_OnClubCost(GameAgent agent,SHMUser user){
		CMD_ChipInfo cmd = new CMD_ChipInfo();
		cmd.m_lUid = (long) user.getUid();
		cmd.m_lTotalCoin = (long) user.getCoin(0);
		cmd.m_lTotalGem = (long) user.getGem(0);
		cmd.m_lTicket = 0L;

		String sData = cmd.getJsonData();
		agent.SendMessage(sData);
	}
	public void Handle_OnAgentReg(GameAgent agent){
		CMD_DlInfo info = new CMD_DlInfo();
		info.dl = 1;
		String sData = info.getJsonData();
		agent.SendMessage(sData);
	}
	public void Handle_OnChip(GameAgent agent, JSONObject root) {
		try {
			if (root.has("uid")) {
				Integer uid = root.optInt("uid");
				if(uid == 0)
					return;
				SHMUser user = getUserInfo(uid);
				if (user != null) {
					CMD_ChipInfo cmd = new CMD_ChipInfo();
					cmd.m_lUid = (long) uid;
					cmd.m_lTotalGem = (long) (user.getGem(0));
					cmd.m_lTotalCoin = (long) (user.getCoin(0));
					cmd.m_lTicket = 0L;
					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}

	// 查询金币
	public void Handle_OnSongbi(GameAgent agent, JSONObject root) {
		Integer _Uid = agent.getUid();
		try {

			Integer from_uid = _Uid;

			Integer to_uid = root.optInt("to_uid");

			SHMUser from_user = getUserInfo(from_uid);
			SHMUser to_user = getUserInfo(to_uid);

			Integer songGem = root.optInt("songGem");

			Integer songCoin = root.optInt("songCoin");

			CMD_S_SongBi cmd = new CMD_S_SongBi();

			cmd.from_uid = from_uid;
			cmd.to_uid = to_uid;

			cmd.songGem = songGem;
			cmd.songCoin = songCoin;

			if (from_user != null && to_user != null) {
				if (from_user.getGem(0) >= songGem && from_user.getCoin(0) >= songCoin) {
					cmd.cbResult = 0;

					cmd.m_lFromGem = from_user.getGem(0 - songGem);
					cmd.m_lFromCoin = from_user.getCoin(0 - songCoin);

					cmd.m_lToGem = to_user.getGem(0 + songGem);
					cmd.m_lToCoin = to_user.getCoin(0 + songCoin);
				} else {
					cmd.cbResult = 2;
				}
			} else {
				cmd.cbResult = 1;
			}

			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}
	public void GetChangedUser(List<Integer> vecUser) {

		for (Integer uid : m_mapUser.keySet()) {
			SHMUser user = m_mapUser.get(uid);
			if (user.getUpdateTime() != 0 && user.getUpdateTime() > user.getLastIndbTime()) {
				vecUser.add(uid);
			}
		}
	}


	public GameAgent getGameAgent(int to_user){
		if(m_mapLinkSession.containsKey(to_user)){
			int cid = m_mapLinkSession.get(to_user);			
			GameAgent agent = GameAgent.agents.get(cid);
			return agent;
		}else{
			return null;
		}
	}
	public void onSend(int to_user, String string) {
		if (m_mapLinkSession.containsKey(to_user)) {
			int cid = m_mapLinkSession.get(to_user);
			GameAgent.Send(cid, string);
		}else{
			System.out.println("dthall can no find user:" + to_user);
		}
	}


	public void Handle_OnBindAgent(GameAgent agent, JSONObject root) {
		int agent_id = 0;
		Integer _Uid = agent.getUid();
		{
			agent_id = root.optInt("agent");

			SHMUser shmuser = getUserInfo(_Uid);
			CMD_S_BindAgent cmd = new CMD_S_BindAgent();
			cmd.cbResult = 1;
			cmd.m_lUid = _Uid.longValue();
			cmd.m_lAgentID = ((Integer) agent_id).longValue();

			if (shmuser != null && agent_id != 0 && agent_id != shmuser.getAgent(0)) {
				CHttpClient c = new CHttpClient();
				String strResponse = c.reguserinfo(shmuser.getUid(), agent_id, shmuser.getNickName(null), "", "");
				if (strResponse == null) {
					cmd.cbResult = 4;
				} else {
					JSONObject value = JSONObject.fromObject(strResponse);

					String code = value.optString("code");
					String msg = value.optString("msg");
					if ("OK".equals(code)) {
						cmd.cbResult = 0;
						shmuser.getAgent(agent_id);
						shmuser.getGem(15);
						//更新agent
						DbInfoMgr.getInstance().Handle_OnUpdateBindAgent(_Uid, agent_id);
					} else {
						String errcode = value.optString("errcode");
						if ("101".equals(errcode)) {
							cmd.cbResult = 1;
						} else if ("102".equals(errcode)) {
							cmd.cbResult = 2;
						} else {
							cmd.cbResult = 3;
							if (shmuser.getAgent(0) == 0) {
								shmuser.getAgent(agent_id);
							}
						}
					}
				}
				cmd.m_lTotalGem = shmuser.getGem(0).longValue();
				cmd.m_lTotalCoin = shmuser.getCoin(0).longValue();
			} else {
				cmd.cbResult = 3;
			}
			String sData = cmd.getJsonData();
			agent.SendMessage(sData);
			// onSend(_Uid,sData);
		}
	}
	public void Handle_OnApplyAgent(GameAgent agent, JSONObject root) throws Exception {
		System.out.println("deal Handle_OnApplyAgent msg");
		JSONObject info =  root.getJSONObject("certifactInfo");		
		String phone = info.getString("phone"); // 玩家手机号
		String uid = String.valueOf(info.getLong("uid"));// 玩家uid
		String nickname = info.getString("nickName");// 玩家昵称
		String occupation = info.getString("occupation");// 职业
		String wechat = info.getString("wechat");// 微信
		String mailContent= "微信: " + wechat + " uid: " + uid + "  手机: " + phone + " 职业: " + occupation;
		String area = info.optString("area");
		MailSender.sendApplyAgentMaiL(mailContent,area);
	}
	public void Handle_OnKeFuSuggest(GameAgent agent, JSONObject root) throws Exception {
		JSONObject info =  root.getJSONObject("suggest");
		System.out.println("deal Handle_OnKeFuSuggest msg");
		String content = info.getString("content");
		String phone = info.getString("phone"); // 玩家手机号
		String uid = String.valueOf(info.getLong("uid"));// 玩家uid
		String nickname = info.getString("nickName");// 玩家昵称
		String mailContent= "昵称：" + nickname + "电话：" + phone + "正文： " + content;
		String area = info.optString("area");
		MailSender.sendSuggestMaiL(mailContent,area);
	}
	public UserRedisInfo getSafeUserRedisInfo(int uid){
		String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
		UserRedisInfo info = null;
		if(data == null){
			info = new UserRedisInfo();
			SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
			if(shmUser != null){
				info.setBasicInfo(uid, shmUser.getNickName(null),this.Handle_OnGetUserAvatar(uid));
			}
			DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
		}else{
			info =  new UserRedisInfo(JSONObject.fromObject(data));
		}
		return info;
	}
	public boolean OnRecv(GameAgent agent, JSONObject root) {
		try {
			String command = root.optString("command");
			if(command.equals("heart")){
				m_qpGameMgr.Handle_OnHeart(agent,root);
				return true;
			}else if(command.equals("clubmsg")){
				ClubMgr.getInstance().HandleOn_ClubRequest(agent, root);
				return true;
			}
			if ("hall_login".equals(command)) {
				System.out.println("=================登录请求");
				Handle_OnLogin(agent, root, agent.getCID());
			} else if("dwc_login".equals(command)){
				System.out.println("=================登录请求");
				Handle_OnLogin(agent, root, agent.getCID());
			} else if ("hall_wxlogin".equals(command)) {
				System.out.println("=================微信登录请求");
				Handle_OnWXLogin(agent, root, agent.getCID());
			} else if("res_connection".equals(command)){
				System.out.println("=================用户重新链接");
				Handle_Res_Connection(agent, root, agent.getCID());
			} else if ("hall_chip".equals(command)) {
				Handle_OnChip(agent, root);
			} else if("socket_".equals(command)){
				
			} else {
				switch (command) {
				case "dwc_cmd":{
					return DwcGameMgr.getInstance().HandleOn_DwcRequest(agent, root);
				}
				case "user_login_record":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					UserRedisInfo info = null;
					if(data == null){
						info = new UserRedisInfo();
						info.setBasicInfo(uid, shmUser.getNickName(null), this.Handle_OnGetUserAvatar(uid));
						DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					}else{
						info =  new UserRedisInfo(JSONObject.fromObject(data));
					}
					info.addUserLoginRecord();
					DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					
					JSONObject rev = new JSONObject();
					rev.put("command","user_login_record");
					rev.put("data", info.getUserLoginRecord());
					
					agent.SendMessage(rev.toString());
					break;
				}
				case "userdraw_login_record":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					int addgem = root.optInt("gem");
					int addcoin = root.optInt("coin");
					shmUser.getGem(addgem);
					shmUser.getCoin(addcoin);
					CMD_ChipInfo cmd = new CMD_ChipInfo();
					cmd.m_lUid = (long) shmUser.getUid();
					cmd.m_lTotalCoin = (long) shmUser.getCoin(0);
					cmd.m_lTotalGem = (long) shmUser.getGem(0);
					cmd.m_lTicket = 0L;

					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					UserRedisInfo info = null;
					if(data == null){
						info = new UserRedisInfo();
						info.setBasicInfo(uid, shmUser.getNickName(null), this.Handle_OnGetUserAvatar(uid));
						DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					}else{
						info =  new UserRedisInfo(JSONObject.fromObject(data));
					}
					info.setLoginDrawed();
					DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					break;
				}
				case "user_drawreward_num":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					UserRedisInfo info = null;
					if(data == null){
						info = new UserRedisInfo();
						info.setBasicInfo(uid, shmUser.getNickName(null), this.Handle_OnGetUserAvatar(uid));
						DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					}else{
						info =  new UserRedisInfo(JSONObject.fromObject(data));
					}
					DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					
					JSONObject rev = new JSONObject();
					rev.put("command","user_drawreward_num");
					rev.put("num", info.getUserDrawRewardNum());
					agent.SendMessage(rev.toString());
					break;
				}
				case "user_use_drawreward":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					int addgem = root.optInt("gem");
					shmUser.getGem(addgem);
					CMD_ChipInfo cmd = new CMD_ChipInfo();
					cmd.m_lUid = (long) shmUser.getUid();
					cmd.m_lTotalCoin = (long) shmUser.getCoin(0);
					cmd.m_lTotalGem = (long) shmUser.getGem(0);
					cmd.m_lTicket = 0L;

					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					UserRedisInfo info = null;
					if(data == null){
						info = new UserRedisInfo();
						info.setBasicInfo(uid, shmUser.getNickName(null), this.Handle_OnGetUserAvatar(uid));
						DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					}else{
						info =  new UserRedisInfo(JSONObject.fromObject(data));
					}
					info.addUserDrawRewardNum(-1);
					DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					break;
				}
				case "mail":{
					//MailMgr.getInstance().Handle_OnMailMsg(agent, root);
					break;
				}
				case "hall_set_gametype":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null){
						return false;
					}
					String type = root.optString("gameType");
					m_gameMgr.setUserGameType(uid, type);
					break;
				}
				case "hall_get_userdata":{
					int uid = agent.getUid();
					SHMUser shmUser = getUserInfo(uid);
					if(shmUser == null){
						return false;
					}
					String type = root.optString("gameType");
					String dataType = root.optString("dataType");
					String [] segment = dataType.split(";");
					JSONObject rev = DbInfoMgr.getInstance().getOtherGameUserData(type, uid,segment);
					rev.put("command", "hall_get_userdata");
					agent.SendMessage(rev.toString());
					break;
				}
				case "hall_set_userdata":{
					int uid = agent.getUid();
					SHMUser shmUser = getUserInfo(uid);
					if(shmUser == null){
						return false;
					}
					String type = root.optString("gameType");
					String data = root.optString("userData");
					DbInfoMgr.getInstance().setOtherGameUserData(type,uid,JSONObject.fromObject(data));
					break;
				}
				case "hall_get_gamerank":{
					m_wxGameMgr.OnRecv(agent, root);
					break;
				}
				case "hall_rank_profile":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					String text1 = root.optString("text1");
					String text2 = root.optString("text2");
					
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					UserRedisInfo info = null;
					if(data == null){
						info = new UserRedisInfo();
						info.setBasicInfo(uid, shmUser.getNickName(null), this.Handle_OnGetUserAvatar(uid));
					}else{
						info =  new UserRedisInfo(JSONObject.fromObject(data));
					}
					info.setUserGoldRankProfile(text1, text2);
					DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					break;
				}
				case "hall_rich_rank":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					List<String> top = DbInfoMgr.getInstance().getGoldRankInfoTop50();
					CMD_Rank_Rich50_Info cmd = new CMD_Rank_Rich50_Info();
					cmd.m_topInfo = top;

					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					break;
				}
				case "client_server_gg":{
					String text = root.optString("txt");
					String type = root.optString("type");
					String clubid = root.optString("clubid");
					String time = "5";
					net.sf.json.JSONObject pub = new net.sf.json.JSONObject();
					pub.put("command","public_push_gg");
					pub.put("value1","" + type);
					pub.put("value2","" + text);
					pub.put("value3","" + time);
					AdminRedis.getInstance().pubAdminSubMsg(pub);
					
					if(clubid != null && !clubid.equals("")){
						GongGaoPack gg = new GongGaoPack();
						gg.type = type;
						gg.txt = text;
						gg.time = time;
						gg.createTime = System.currentTimeMillis() / 1000;
						DbInfoMgr.getInstance().setClubBroadCastGG(clubid,JsonUtils.serialize(gg));
					}
					break;
				}
				case "hall_get_agentlevel":{
					//1可以打开uu，2可以打开dwc，3可以打开所有的
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					if(!AdminMgr.getInstance().isSupportGoldDwc() || shmUser.getIsAgent() == 0){
						CMD_UserAgentLevel cmd = new CMD_UserAgentLevel();						
						cmd.level = 0;
						String sData = cmd.getJsonData();
						agent.SendMessage(sData);
						return false;
					}
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					if(data == null){
						CMD_UserAgentLevel cmd = new CMD_UserAgentLevel();						
						cmd.level = 0;
						String sData = cmd.getJsonData();
						agent.SendMessage(sData);
						return false;
					}
					UserRedisInfo info =  new UserRedisInfo(JSONObject.fromObject(data));
					CMD_UserAgentLevel cmd = new CMD_UserAgentLevel();						
					cmd.level = info.getGoldAgentLevel(uid);
					cmd.dwcLevel = info.json.optInt("agentLevel");
					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					return false;
				}
				case "hall_today_charge":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					CMD_TodayCharge cmd = new CMD_TodayCharge();
					String data = DbInfoMgr.getInstance().getUserTodayChargeInfo(uid);
					if(data == null){
						cmd.todaysum = 0;
					}else{
						UserChargeInfo info = JsonUtils.deserialize(data, UserChargeInfo.class);
						cmd.todaysum = info.money;
					}
					cmd.todaylimit = DbInfoMgr.getInstance().getUserOneDayChargeThreahold();
					String sData = cmd.getJsonData();
					agent.SendMessage(sData);					
					break;
				}
				case "hall_get_useritem":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					UserRedisInfo info = null;
					if(data == null){
						info = new UserRedisInfo();
						info.setBasicInfo(uid, shmUser.getNickName(null), this.Handle_OnGetUserAvatar(uid));
						DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					}else{
						info = new UserRedisInfo(JSONObject.fromObject(data));
					}
					CMD_UserItem cmd = new CMD_UserItem();
					info.getAllItems(cmd.items);
					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					break;
				}
				case "hall_use_useritem":{
					int uid = agent.getUid();
					int index = root.optInt("index");
					if(index < 1 || index > 30)
						break;
					String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
					if(data == null){
						break;
					}
					UserRedisInfo info =  new UserRedisInfo(JSONObject.fromObject(data));
					int count = info.getUserItemCount(index);
					if(count <= 0){
						SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
						if(shmUser == null)
							return false;
						if(index == 4 || index == 6 || index == 7 || index == 10){
							shmUser.getCoin(-500);
						}else{
							shmUser.getGem(-2);
						}
					}else{
						info.useUserItem(index);
					}
					DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
					break;
				}
				case "hall_buy_useritem":{
					int uid = agent.getUid();
					int index = root.optInt("index");
					if(index < 1 || index > 13)
						return false;
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					if(index == 4 || index == 6 || index == 7 || index == 10 || index == 13){
						//cost coinx500
						int coin = shmUser.getCoin(0);
						int cost = 500;
						if(index == 13)
							cost = 50000000;
						if(coin >= cost){
							String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
							if(data == null){
								return false;
							}
							UserRedisInfo info =   new UserRedisInfo(JSONObject.fromObject(data));
							info.buyUserItem(index, 1);
							DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
							shmUser.getCoin(-cost);
						}
					}else{
						//cost gemx2
						int gem = shmUser.getGem(0);
						if(gem >= 2){
							String data = DbInfoMgr.getInstance().getUserRedisSaveInfo(String.valueOf(uid));
							if(data == null){
								return false;
							}
							UserRedisInfo info =  new UserRedisInfo(JSONObject.fromObject(data));
							info.buyUserItem(index, 1);
							DbInfoMgr.getInstance().setUserRedisSaveInfo(String.valueOf(uid),info.getUserInfoStr());
							shmUser.getGem(-2);
						}
					}
					break;
				}
				case "hall_use_rank_inclub":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					CMD_Use_Rank_InClub cmd = new CMD_Use_Rank_InClub();
					if(this.m_userRankInClub){
						cmd.use = 1;
					}else{
						cmd.use = 0;
					}
					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					break;
				}
				case "hall_duihuan_gem_uu":{
					int currgem = root.optInt("gem");
					int currcoin = root.optInt("coin");
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					int hasgem = shmUser.getGem(0);
					int hascoin = shmUser.getCoin(0);
					if(currgem > hasgem){
						//UU兑换gem
						
					}else{
						//gem 兑换UU
					}
					shmUser.getGem(currgem - hasgem);
					shmUser.getCoin(currcoin - hascoin);
					CMD_DuiHuan_GemUU cmd = new CMD_DuiHuan_GemUU();
					cmd.currCoin = currcoin;
					cmd.currGem = currgem;
					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					break;
				}
				case "uu_buchang":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					int fzuid = root.optInt("fzuid");
					int num = root.optInt("num");
					CMD_UU_Quit_BuChang cmd = new CMD_UU_Quit_BuChang();
					SHMUser fzUser = dthall.getInstance().getUserInfo(fzuid);
					if(fzUser == null || fzuid == uid || num > shmUser.getCoin(0)){
						cmd.success = 0;						
					}else{
						fzUser.getCoin(num);
						//记录
						UserGoldChange.hanleGoldChangeBuChang(fzUser, num, UserGoldChange.reason19);
						shmUser.getCoin(-num);
						UserGoldChange.hanleGoldChangeBuChang(fzUser, 0 - num, UserGoldChange.reason19);
						cmd.fzuid = fzuid;
						cmd.senderuid = uid;
						cmd.fzcoin = fzUser.getCoin(0);
						cmd.sendercoin = shmUser.getCoin(0);
						cmd.coin = num;
						cmd.success = 1;
					}
					String sData = cmd.getJsonData();
					agent.SendMessage(sData);
					dthall.getInstance().onSend(fzuid,sData);
					break;
				}
				case "hall_buy_nobind":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					String sheng = root.getString("sheng");
					String city = root.getString("city");
					MailSender.sendNoBindBuy(sheng, city);
					break;
				}
				case "hall_cancel_bind":{
					int uid = agent.getUid();
					SHMUser shmUser = dthall.getInstance().getUserInfo(uid);
					if(shmUser == null)
						return false;
					if(shmUser.getGem(0) <= 88){
						CMD_CancelBind cmd = new CMD_CancelBind();
						cmd.result = -1;
						cmd.gem = 0;
						String sData = cmd.getJsonData();
						agent.SendMessage(sData);
					}else{
						boolean ok = DbInfoMgr.getInstance().cancelUserBindInfo(uid);
						if(ok){
							shmUser.getGem(-88);
							CMD_CancelBind cmd = new CMD_CancelBind();
							cmd.result = 1;
							cmd.gem = shmUser.getGem(0);
							String sData = cmd.getJsonData();
							agent.SendMessage(sData);
						}else{
							CMD_CancelBind cmd = new CMD_CancelBind();
							cmd.result = 0;
							String sData = cmd.getJsonData();
							agent.SendMessage(sData);
						}
					}
					break;
				}
				case "hall_user_invitor":{
					Handle_OnGetUserInvitor(agent,root);
					break;
				}
				case "hall_rank_info":{
					Handle_OnTop100RankInfo(agent,root);
					break;
				}
				case "hall_prevrank_info":{
					Handle_OnPrevTop100RankInfo(agent,root);
					break;
				}
				case "hall_myrank_info":{
					Handle_OnMyRankInfo(agent,root);
					break;
				}
				case "hall_isget_huafei":{
					Handle_OnIsUserGotHuaFei(agent);
					break;
				}
				case "hall_setuser_draw_huafei":{
					Handle_OnSetUserDrawHuaFei(agent);
					break;
				}
				case "hall_bind_inviter":{
					Handle_OnBindInviter(agent,root);
					break;
				}
				case "hall_user_room":
					m_qpGameMgr.Handle_OnUserRoom(agent, root);
					break;
				case "hall_create_room":
					m_qpGameMgr.Handle_OnCreateRoom(agent, root);
					break;
				case "hall_join_room":
					m_qpGameMgr.Handle_OnJoinRoom(agent, root);
					break;
				case "hall_return_room":
					m_qpGameMgr.Handle_OnReturnRoom(agent, root);
					break;
				case "hall_dismiss_room":
					m_qpGameMgr.Handle_OnDismissRoom(agent, root);
					break;
				case "hall_bind_agent":
					Handle_OnBindAgent(agent, root);
					break;
				case "hall_user_avatar":
					Handle_OnUserAvatar(agent, root);
					break;
				case "hall_share_timeline":
					Handle_OnShareTimeline(agent, root);
					break;
				case "hall_duihuan":
					Handle_OnDuiHuan(agent, root);
					break;
				case "Gps_Data":{
					Handle_OnGetGpsData(agent,root);
					break;
				}
				case "Gps_Loc":{
					Handle_OnGetLocationData(agent,root);
					break;
				}				
				case "hall_apply_agent":
					Handle_OnApplyAgent(agent, root);
					break;
				case "hall_kefu_suggest":
					Handle_OnKeFuSuggest(agent, root);
					break;
				case "zjhmsg":
				case "zjhmsg10":
				case "xlchmsg":
				case "niuniumsg":
				case "sgmsg":
				case "slwhmsg":
				case "ttzmsg":
				case "fjsszmsg":
				case "sszliumsg":
				case "ddzmsg":
				case "pdkmsg":
				case "ntpdkmsg":
				case "cpmsg":
				case "sjmsg":
				case "mjmsg":
				case "bjzmsg":
				case "dgtmsg":
				case "fksgjmsg":
				case "brsgjmsg":
				case "FGRoomList":
				case "slhbmsg":
				case "cqsscmsg":
				case "pk10msg":
				case "dhsscmsg":
				case "niuniumsg10":
					m_qpGameMgr.OnRecv(agent, root);
					break;
				case "hall_song_bi":
					Handle_OnSongbi(agent, root);
					break;
				default:
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}

		return false;
	}

	public void DiaoXian(int lUid){
		if (m_mapLinkSession.containsKey(lUid)) {
			int oldLinkCID = m_mapLinkSession.get(lUid);
			try {
				GameAgent old_agent = GameAgent.find_client(oldLinkCID);
				if (old_agent != null) {
					old_agent.Disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			m_mapLinkSession.remove(lUid);
			if (m_mapLinkUser.containsKey(oldLinkCID)) {
				m_mapLinkUser.remove(oldLinkCID);
			}
		}
	}
	public void FengHao(int lUid) {
		this.DiaoXian(lUid);
		GameConfig.AddFengHaoUid(lUid);
	}

	public void DiaoXianAll() {
		if(GlobalSetting.getInstance().getSelfNodeInfo().nodeType == NodeType.GATE){
			HandlerWrapperMgr.getInstance().closeAllChannelHandler();
		}
	}

	public String ServerInfo() {
		String infos ="";
		infos += "曾经登录用户总数:"+ m_mapLinkSession.size()+"<br/>";
		infos += "目前登录用户总数:"+ GameAgent.agents.size()+" <br/>";
		return infos;
	}	
	
	public void handGetPai(String text){
		int pai = Integer.parseInt(text);
		CMD_S_AgentGG cmd = new CMD_S_AgentGG();
		cmd.GGtxt = text;
		String sData = cmd.getJsonData();
		GameAgent.Broadcast(sData);
	}
}
